package com.dormitoryAdministratorSystem.dao.clazz.impl;

import com.dormitoryAdministratorSystem.dao.clazz.IClassDao;
import com.dormitoryAdministratorSystem.entity.clazz.ClassBean;
import com.dormitoryAdministratorSystem.util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ClassDaoImpl implements IClassDao {
    @Override
    public List<ClassBean> getAllClasses() {
        String sql = "select cid,cname,openTime,teacher from t_class";
        return getClassList(sql);
    }

    @Override
    public List<ClassBean> getClassByPage(String sql, Object... parms) {
        return getClassList(sql,parms);
    }

    @Override
    public int getClassTolNum(String sql, Object... parms) {
        ResultSet rSet = DBUtil.excuteQuery(sql,parms);
        int result = 0;

        try {
            while(rSet.next()){
                result = rSet.getInt("cNum");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }

        return result;
    }

    @Override
    public int insertClass(ClassBean classBean) {
        String sql = "insert into t_class values(null,?, ?, ?)";

        return DBUtil.excuteUpdate(
                sql,
                classBean.getCName(),
                classBean.getOpenTime(),
                classBean.getTeacherName()
        );
    }

    @Override
    public int deleteClassById(int classId) {
        String sql = "delete from t_class where cid = ?";
        return DBUtil.excuteUpdate(sql,classId);
    }

    public ClassBean getClassBean(int cid){
        String sql = "select * from t_class where cid = ?";
        ClassBean c = null;

        ResultSet rSet = DBUtil.excuteQuery(sql,cid);

        try{
            while(rSet.next()){
                c = getClassBean(rSet);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }

        return c;
    }

    private ClassBean getClassBean(ResultSet rSet) throws SQLException {
        ClassBean c = new ClassBean();
        c.setCId(rSet.getInt("cid"));
        c.setCName(rSet.getString("cname"));
        c.setOpenTime(rSet.getDate("openTime"));
        c.setTeacherName(rSet.getString("teacher"));

        return c;
    }

    private List<ClassBean> getClassList(String sql, Object... prams){
        List<ClassBean> list = new ArrayList<>();
        ResultSet rSet = DBUtil.excuteQuery(sql,prams);

        try {
            while(rSet.next()){
                list.add(getClassBean(rSet));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return list;
    }
}
